<template>
  <base-modal width="820px" class="task-approve-dialog" ref="approveSettingWindow" :title="title" :show.sync="visible" @closed="handleClose">
   <div v-for="(pItem, index) in approveConditions" :key="pItem._key">
      <div class="criteria-item">
        <div class="criteria-item-title">
          <div class="title-name">{{$t('zhongqi.setting.conditionGroup')}}{{(index + 1)}}</div>
          <div class="close" v-if="(approveConditions.length !== 1)" @click="removeItem(index)">
            <i class="el-icon-close"></i>
          </div>
        </div>
        <div class="criteria-item-detail" v-for="(ele, ind) in pItem.list" :key="ind">
          <div class="fisrt-select">
            <el-select v-model="ele.module" @change="update($event, ele)">
              <el-option
                v-for="item in optionsList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
                @click.native="clearConditionSearchItem(ele.conditionItem)"
              >
              </el-option>
            </el-select>
          </div>
          <ConditionSearchItem 
            v-if="visible"
            :fields="ele.fieldsOptions"
            :conditionItem="ele.conditionItem"
            :isShowInitValue="true"
            :isClearValue="true"
            :rule-module="ele.module"
            />
          <div class="criteria-item-detail-operatos">
            <span class="del-icon" @click="removeItemDetail(index, ind)">
              <i class="iconfont icon-delete"></i>
            </span>
          </div>
          
        </div>
        <div class="add-item-detail" @click="addItemDetail(index)">
          + {{$t('zhongqi.setting.andConditions')}}
        </div>
      </div>
      <div class="split-text" v-if="(index !== approveConditions.length -1)">{{$t('zhongqi.setting.orText')}}</div>
      
    </div>

    <div>
      <el-button v-if="(approveConditions.length > 0)" type="primary" @click="addItem">+ {{$t('zhongqi.setting.orConditions')}}</el-button>
      <el-button v-else type="primary" @click="addItem">+ {{ $t('zhongqi.setting.addConditions') }}</el-button>
    </div>

    <div slot="footer" class="dialog-footer">
      <el-button type="plain-third" @click="visible = false">{{$t('common.base.cancel')}}</el-button>
      <el-button type="primary" @click="saveSetting">{{$t('common.base.save')}}</el-button>
    </div>
  </base-modal>

</template>
<script>
import ConditionSearchItem from '@src/component/AdvancedSearch/ConditionSearchItem.vue'
import * as TaskApi from '@src/api/TaskApi.ts';
import { t } from '@src/locales';
import _ from 'lodash';

export default {
  name: 'approve-setting-criteria',
  props: {
    isFromAdvanced: {
      type: Boolean,
      default: false
    },
    taskTypeId: {
      type: String,
      default: ''
    },
    optionMaps: {
      type: Object,
      default: () => ({})
    },
    flowType: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      title: `${t('zhongqi.setting.conditions')}`,
      size: 'medium',
      visible: false,
      options: [
        {
          label: `${t('common.base.systemKeyword.task')}`,
          value: 'task'
        },
      ],
      defaultType: 'task',
      conditionItem: {},
      approveConditions: [], // 传过来的条件组
      defaultTaskList: [],// 初始化的工单filed接口
      defaultTaskReceiptList: [],// 初始化的工单回执filed接口
      defaultTaskReceiptAmountList: [], // 工单金额的接口
      level: 1, //当前的审批等级
    
    }
  },
  components: {
    ConditionSearchItem
  },
  computed: {
    optionsList() {
      // 指派和开始节点，只展示工单
      if (this.flowType === 'start' || this.flowType === 'allot' || this.isFromAdvanced || this.flowType === 'create') {
        return this.options
      } else {
        let finishOptions = JSON.parse(JSON.stringify(this.options)) 
        finishOptions.push(
          {
            label: this.$t('common.zhongqi.taskReceipt'),
            value: 'task_receipt'
          },
          {
            label: this.$t('zhongqi.setting.taskReceiptAmount'),
            value: 'task_receipt_amount'
          }
        )
        return finishOptions
      }
    },
  },

  mounted() {

  },
  methods: {
    // 切换清空数据
    clearConditionSearchItem (data) {
      this.$set(data, 'comp', '');
      this.$set(data, 'field', null);
      this.$set(data, 'operator', '');
      this.$set(data, 'fieldName', '');
      this.$set(data, 'value', null)
    },

    handleClose() {
      this.visible = false
    },
    openDialog(conditions, level) {
      this.approveConditions = [] // 清空之前的
      if (conditions && conditions.length > 0) {
        this.approveConditions = (_.cloneDeep(conditions)).map((item, index) => {
          return {
            _key: index,
            list: item
          }
        })
        console.log(this.approveConditions, '------------------this.approveConditions')
      } else {
        // 默认展示一条空的数据
        this.addItem()
      }
      this.level = level
      this.visible = true
    },
    async update(val, item) {
      if(val === 'task_receipt_amount') {
        let params = {
          moduleId: this.taskTypeId,
        }
        // 需要重新请求接口，防止是在当前页面更新的规则
        await TaskApi.getSettlementRule(params).then((res) => {
        if (res.result) {
          res.result.forEach((item) => {
            item.formType = 'number'
            item.operator = ''
            item.displayName = item.ruleName
            item.fieldName = item.ruleName
            item.business = item.business
          })
          this.$set(item, 'fieldsOptions', res.result);
          this.optionMaps['task_receipt_amount'] = res.result

        }
      })

      } else {
        this.$set(item, 'fieldsOptions', this.optionMaps[val]);
      }
    },

    // 添加或条件
    addItem() {
      // 添加条件组
      this.approveConditions.push({
        list: [
          {
            module: "", // 模块 工单/工单回执/工单回执金额
            conditionItem: {
              fieldName: "", //  子模块的fieldName
              operator: "", // 操作符
              value: [], // 选中的结果值
              comp: "", // 条件的控件类型
              field: null
            }
          }
        ],
        _key: Math.random()
      })
    },
    // 添加且条件
    addItemDetail(index) {
      this.approveConditions[index].list.push(
        {
          module: "", // 模块 工单/工单回执/工单回执金额
          conditionItem: {
            fieldName: "", //  子模块的fieldName
            operator: "", // 操作符
            value: [], // 选中的结果值
            comp: "", // 条件的控件类型
            field: null
          }
        },
      )
    },

    // 删除条件组
    removeItem(index) {
      this.approveConditions.splice(index, 1)
    },

    removeItemDetail(index, itemIndex) {
      if (this.approveConditions[index].list.length === 1) {
        // 条件组内只有一个条件的话，点击删除，就删除整个条件组
        this.approveConditions.splice(index, 1)
      } else {
        this.approveConditions[index].list.splice(itemIndex, 1)
      }
    },
    
    saveSetting() {
      let messageList = []
      this.approveConditions.forEach((item, index)=> {
        item.list.forEach((ele)=> {

          console.log(ele.conditionItem, 'ele.conditionItem.')
          // BUG 需要判断一个null
          if (ele.conditionItem.value === null || ele.conditionItem.value.length === 0) {
            let text = `${t('zhongqi.setting.conditionGroup')}`
            messageList.push(`${text}${index + 1}`)
          } else {
            // 转为提交接口的字段
            ele.conditionItem.valueList = this.filterData(ele.conditionItem.comp, ele.conditionItem.value)
            ele.conditionItem.valueStr = JSON.stringify(ele.conditionItem.value) 
            ele.conditionItem.formType = ele.conditionItem.field.formType
            // 新增的规则名称字段
            ele.conditionItem.subFieldName = ele.conditionItem.field.business
          }
        })
      })

      if (messageList.length > 0) {
        let messageText = messageList.toString()

        this.$platform.notification({
          title: `${messageText}${t('zhongqi.setting.saveCheckText')}`,
          type: 'error'
        });
      } else {
        this.visible = false
        this.$emit('getCondition', this.approveConditions.map(item => item.list), this.level)

        console.log(this.approveConditions, 'this.approveConditionsthis.approveConditions')
      }
    },

    // 转换为提交的数据 valueList为数组格式
    filterData(comp, value) {
      let filterArr = []
      if (comp === 'user-search') {
        return value.map(item => item.id);
      } else if (comp === 'date-search' || comp === 'select-search') {
        // 时间本身就是数组形式
        return value
      }else {
        // 其他类型的都转为数组
        filterArr.push(value)
        return filterArr
      }
    }
  }
}
</script>
<style lang="scss" scoped>

.task-approve-dialog {
  ::v-deep .base-modal-body {
    padding: 12px 20px !important;
  }
}
.criteria-item {
  padding: 12px 16px;
  background: #F5F5F5;
  margin: 12px 0;
  .criteria-item-title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 8px;
    .title-name {
      font-size: 14px;
      color: #262626;
      font-weight: bold;
      line-height: 20px;
      .require-icon {
        // color: #000;
        // color: $text-color-secondary;
      }
    }
  }
  .criteria-item-detail {
    display: flex;
    align-items: center;
    margin-bottom: 12px;
    .condition-search-item__condition-select .el-select {
      width: 140px;
    }
    .fisrt-select {
      width:160px;
      margin-right: 12px;
    }
    .criteria-item-detail-operatos {
      text-align: center;
      .del-icon {
        display: inline-block;
        width: 40px;
        line-height: 30px;
        color: $text-color-secondary;
        cursor: pointer;
      }
    }
  }

  .add-item-detail {
    width: 60px;
    color: $color-primary-light-6;
    font-size: 14px;
    font-weight: 400;
    margin-top: 12px;
    cursor: pointer;
  }
}
.split-text {
  width: 14px;
  height: 20px;
  font-size: 14px;
  font-family: PingFangSC-Regular, PingFang SC;
  font-weight: 400;
  color: #595959;
  line-height: 20px;
}

.approve-footer {
  height: 52px;
  padding: 10px;
  text-align: right;
}
</style>